<template>
  <div class="dashboard-container">
    <el-row :gutter="10">
      <el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24">
        <el-card style="height: 150px; padding: 10px" shadow="hover">
          <div class="card-content">
            <div class="avatar-container">
              <el-image class="avatar" :src="avatar" :preview-src-list="srcList" />
            </div>
            <div class="info-container">
              <div class="greeting-container">
                <p class="greeting-message">{{ formatHour }}尊敬的 {{ name }}</p>
                <p>愿您的每一天都充满创新与发现！</p>
              </div>
            </div>
            <div class="stats-container">
              <div class="statistic-item">
                <p class="statistic-key">待办</p>
                <p class="statistic-value">{{ jobCount }}/100</p>
              </div>
              <div class="statistic-item">
                <p class="statistic-key">用户量</p>
                <p class="statistic-value">{{ userCount.toLocaleString('en-US') }}</p>
              </div>
              <div class="statistic-item">
                <p class="statistic-key">项目数</p>
                <p class="statistic-value">{{ projectCount.toLocaleString('en-US') }}</p>
              </div>
            </div>
          </div>
        </el-card>
      </el-col>

      <el-col :xs="24" :sm="24" :md="24" :lg="16" :xl="16" class="mt15">
        <el-card class="box-card mt-5" shadow="hover">
          <div ref="lineChart" style="width: 100%; height: 600px" />
        </el-card>
      </el-col>

      <el-col :xs="24" :sm="24" :md="12" :lg="8" :xl="8" class="mt15">
        <el-card shadow="hover">
          <template #header>快捷导航</template>
          <div class="box-container">
            <el-card v-for="item in navList" :key="item.title" shadow="hover" class="icon-title-box">
              <div @click="navTo(item.path)">
                <i :class="item.icon" :style="item.style" />
                <h2 class="title">{{ item.title }}</h2>
              </div>
            </el-card>
          </div>
        </el-card>
      </el-col>

      <el-col v-if="hasPerm('sys:login-log:page')" :xs="24" :sm="24" :md="12" :lg="8" :xl="8" class="mt15">
        <el-card shadow="hover">
          <template #header>
            系统日志
            <el-button style="float: right; padding: 3px 0" type="text" @click="navTo('/sys/log')">更多</el-button>
          </template>
          <el-timeline :reverse="false">
            <el-timeline-item
              v-for="(item, index) in loginLogData"
              :type="item.loginStatus == '成功' ? 'success' : 'danger'"
              :key="index"
              :timestamp="item.loginTime"
            >
              {{ item.username }} - {{ item.description }} - {{ item.loginIp }}
            </el-timeline-item>
          </el-timeline>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import { mapGetters } from 'vuex'
import * as echarts from 'echarts'
import loginLogApi from '@/api/sys/login-log'
import { formatHour } from '@/utils/index'

export default {
  name: 'Dashboard',
  computed: {
    ...mapGetters(['avatar', 'name'])
  },
  data() {
    return {
      formatHour: formatHour(),
      srcList: [
        'https://k.sinaimg.cn/n/sinakd20117/0/w800h800/20240127/889b-4c8a7876ebe98e4d619cdaf43fceea7c.jpg/w700d1q75cms.jpg',
        'https://img1.baidu.com/it/u=3995643348,1848098846&fm=253&fmt=auto&app=138&f=JPEG',
        ''
      ],
      navList: [
        { icon: 'el-icon-setting', title: '系统管理', path: '/sys', style: { color: '#67C23A' } },
        { icon: 'el-icon-s-help', title: '系统监控', path: '/monitor', style: { color: '#F56C6C' } }
      ],
      loginLogData: [],
      chartKey: [],
      successData: [],
      errorData: [],
      jobCount: 10,
      projectCount: 666,
      userCount: 888888,
      updateInterval: null
    }
  },
  created() {
    if (this.hasPerm('sys:login-log:page')) {
      this.getLoginLog()
    }
  },
  mounted() {
    this.generateMonthKeys()
    this.initLineChart()
    this.updateInterval = setInterval(() => {
      this.generateMonthKeys()
      this.initLineChart()
    }, 3600000) // 3600000 毫秒等于 1 小时

    window.addEventListener('resize', this.handleResize)
  },
  beforeDestroy() {
    window.removeEventListener('resize', this.handleResize)
    if (this.lineChart) {
      this.lineChart.dispose()
      this.lineChart = null
    }
    clearInterval(this.updateInterval)
  },
  methods: {
    // 生成近一个月的日期键
    generateMonthKeys() {
      const currentDate = new Date()
      const startDate = new Date(currentDate.getFullYear(), currentDate.getMonth() - 1, currentDate.getDate() + 1, 1)
      const endDate = new Date()

      const currentDateCopy = new Date(startDate)
      while (currentDateCopy <= endDate) {
        const month = (currentDateCopy.getMonth() + 1).toString().padStart(2, '0')
        const day = currentDateCopy.getDate().toString().padStart(2, '0')
        const formatKey = `${month}-${day}`

        if (currentDateCopy.getDate() === currentDate.getDate() - 2) {
          this.chartKey.push('两天前')
        } else if (currentDateCopy.getDate() === currentDate.getDate() - 1) {
          this.chartKey.push('一天前')
        } else if (currentDateCopy.getDate() === currentDate.getDate()) {
          const hoursAgo = currentDate.getHours() - currentDateCopy.getHours()
          this.chartKey.push(`${hoursAgo}小时前`)
        } else {
          this.chartKey.push(formatKey)
        }

        // 随机生成成功和失败的数据
        this.successData.push(Math.floor(Math.random() * 60 + 100))
        this.errorData.push(Math.floor(Math.random() * 10 + 5))

        currentDateCopy.setDate(currentDateCopy.getDate() + 1)
      }
    },

    // 获取登录日志
    getLoginLog() {
      loginLogApi.getPage(1, 6, {}).then((res) => {
        this.loginLogData = res.data.records
      })
    },

    // 页面跳转
    navTo(path) {
      this.$router.push(path)
    },

    // 初始化折线图
    initLineChart() {
      this.lineChart = echarts.init(this.$refs.lineChart)
      const lineOptions = {
        title: {
          text: '近一月操作日志统计'
        },
        tooltip: {
          trigger: 'axis'
        },
        legend: {},
        grid: {
          left: '1%',
          right: '4%',
          bottom: '3%',
          containLabel: true
        },
        toolbox: {
          show: true,
          feature: {
            dataZoom: {
              yAxisIndex: 'none'
            },
            dataView: { readOnly: false },
            magicType: { type: ['line', 'bar'] },
            restore: {},
            saveAsImage: {}
          }
        },
        xAxis: {
          type: 'category',
          boundaryGap: false,
          data: this.chartKey
        },
        yAxis: {
          type: 'value',
          axisLabel: {}
        },
        series: [
          {
            name: '成功',
            type: 'line',
            color: 'green',
            data: this.successData,
            markPoint: {
              data: [
                { type: 'max', name: 'Max' },
                { type: 'min', name: 'Min' }
              ]
            },
            markLine: {
              data: [{ type: 'average', name: 'Avg' }]
            }
          },
          {
            name: '失败',
            type: 'line',
            color: 'red',
            data: this.errorData,
            markPoint: {
              data: [
                { type: 'max', name: 'Max' },
                { type: 'min', name: 'Min' }
              ]
            },
            markLine: {
              data: [{ type: 'average', name: 'Avg' }]
            }
          }
        ]
      }
      this.lineChart.setOption(lineOptions)
    },

    // 调整图表大小
    handleResize() {
      if (this.lineChart) {
        this.lineChart.resize()
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.dashboard {
  &-container {
    margin: 30px;
  }
  &-text {
    font-size: 30px;
    line-height: 46px;
  }
}

.box-container {
  display: flex;
  flex-direction: row; /* 设置为横向排列 */
  padding: 0; /* 移除外边距 */
  margin: 0; /* 移除外边距 */
  cursor: pointer;
}

.icon-title-box {
  width: 100px;
  height: 100px;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  border: 1px solid #f2f6fc; /* 边框 */
}

.icon-title-box i {
  padding-left: 10px;
  font-size: 24px; /* 图标大小 */
}

.title {
  margin-top: 5px; /* 图标和标题之间的间距 */
  font-size: 12px; /* 标题字体大小 */
}

.mt-5 {
  margin-top: 5px;
}

.mt15 {
  margin-top: 15px;
}
.card-content {
  display: flex;
  align-items: center;
  height: 100%;

  .avatar-container {
    flex: 0 0 80px;

    .avatar {
      width: 80px;
      height: 80px;
      border-radius: 50%;
    }
  }

  .info-container {
    flex: 1;
    padding-left: 10px;
    display: flex;
    flex-direction: column;
    justify-content: space-between;

    .greeting-container {
      .greeting-message {
        font-weight: bold;
        padding-bottom: 10px;
      }

      p {
        margin: 5px 0;
      }
    }
  }
  .stats-container {
    display: flex;
    justify-content: space-between;

    .statistic-item {
      display: flex;
      flex-direction: column;
      align-items: flex-start;
      margin-left: 100px;

      .statistic-key {
        margin: 0;
        font-weight: bold;
      }
    }
  }
}
</style>
